<template>
  <input
    class="form-input number-input"
    :class="{ 'has-error': hasError, 'disabled': disabled }"
    type="number"
    :value="modelValue"
    :placeholder="placeholder"
    :disabled="disabled"
    :readonly="readonly"
    :min="min"
    :max="max"
    :step="step"
    @input="handleInput"
    @blur="handleBlur"
    @focus="handleFocus"
  />
</template>

<script setup lang="ts">
import { computed } from 'vue';

// 定义组件属性
interface Props {
  modelValue?: string | number;
  placeholder?: string;
  disabled?: boolean;
  readonly?: boolean;
  hasError?: boolean;
  min?: number;
  max?: number;
  step?: number | string;
  precision?: number; // 小数位数
  allowNegative?: boolean; // 是否允许负数
}

// 定义事件
interface Emits {
  (e: 'update:modelValue', value: string): void;
  (e: 'blur', event: Event): void;
  (e: 'focus', event: Event): void;
  (e: 'change', value: string): void;
}

const props = withDefaults(defineProps<Props>(), {
  modelValue: '',
  placeholder: '请输入数字',
  disabled: false,
  readonly: false,
  hasError: false,
  step: 1,
  precision: 2,
  allowNegative: true,
});

const emit = defineEmits<Emits>();

// 格式化数字值
const formatNumber = (value: string): string => {
  if (!value || value === '') return '';
  
  // 移除非数字字符（保留小数点和负号）
  let cleanValue = value.replace(/[^\d.-]/g, '');
  
  // 处理负号
  if (!props.allowNegative) {
    cleanValue = cleanValue.replace(/-/g, '');
  } else {
    // 确保负号只在开头
    const hasNegative = cleanValue.startsWith('-');
    cleanValue = cleanValue.replace(/-/g, '');
    if (hasNegative) {
      cleanValue = '-' + cleanValue;
    }
  }
  
  // 处理小数点
  const parts = cleanValue.split('.');
  if (parts.length > 2) {
    // 只保留第一个小数点
    cleanValue = parts[0] + '.' + parts.slice(1).join('');
  }
  
  // 限制小数位数
  if (parts.length === 2 && parts[1].length > props.precision) {
    cleanValue = parts[0] + '.' + parts[1].substring(0, props.precision);
  }
  
  return cleanValue;
};

// 验证数字范围
const validateRange = (value: string): string => {
  if (!value || value === '' || value === '-') return value;
  
  const numValue = parseFloat(value);
  if (isNaN(numValue)) return '';
  
  if (props.min !== undefined && numValue < props.min) {
    return props.min.toString();
  }
  
  if (props.max !== undefined && numValue > props.max) {
    return props.max.toString();
  }
  
  return value;
};

// 处理输入事件
const handleInput = (event: Event) => {
  const target = event.target as HTMLInputElement;
  let value = target.value;
  
  // 格式化输入值
  const formattedValue = formatNumber(value);
  
  // 如果格式化后的值与原值不同，更新输入框显示
  if (formattedValue !== value) {
    target.value = formattedValue;
  }
  
  emit('update:modelValue', formattedValue);
  emit('change', formattedValue);
};

// 处理失焦事件
const handleBlur = (event: Event) => {
  const target = event.target as HTMLInputElement;
  let value = target.value;
  
  // 失焦时进行范围验证
  const validatedValue = validateRange(value);
  
  if (validatedValue !== value) {
    target.value = validatedValue;
    emit('update:modelValue', validatedValue);
    emit('change', validatedValue);
  }
  
  emit('blur', event);
};

// 处理聚焦事件
const handleFocus = (event: Event) => {
  emit('focus', event);
};
</script>

<style lang="scss" scoped>
.number-input {
  width: 100%;
  padding: 12px 16px;
  border: 1px solid #e0e0e0;
  border-radius: 8px;
  font-size: 16px;
  line-height: 1.4;
  background-color: #ffffff;
  transition: all 0.3s ease;
  
  &:focus {
    outline: none;
    border-color: #007aff;
    background-color: #f8f9ff;
  }
  
  &.has-error {
    border-color: #ff3b30;
    background-color: #fff5f5;
  }
  
  &.disabled {
    background-color: #f5f5f5;
    color: #999999;
    cursor: not-allowed;
  }
  
  &::placeholder {
    color: #c7c7cc;
    font-size: 14px;
  }
}

/* 移除数字输入框的默认箭头 */
.number-input::-webkit-outer-spin-button,
.number-input::-webkit-inner-spin-button {
  -webkit-appearance: none;
  margin: 0;
}

.number-input[type=number] {
  -moz-appearance: textfield;
}
</style>
